package com.tencent.qcloud.qiaoqiao.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.qcloud.qiaoqiao.R;
import com.tencent.qcloud.qiaoqiao.common.utils.TCConstants;
import com.tencent.qcloud.qiaoqiao.login.TCUserMgr;
import com.tencent.qcloud.qiaoqiao.mainui.list.TCVideoInfo;
import com.tencent.qcloud.qiaoqiao.play.TCVodPlayerActivity;
import com.tencent.qcloud.qiaoqiao.ui.BaseFragment;
import com.tencent.qcloud.qiaoqiao.ui.adapter.CollectAdapter;
import com.tencent.qcloud.qiaoqiao.ui.bean.CollectBean;
import com.tencent.qcloud.qiaoqiao.ui.net.FastJsonTools;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpRequest;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpResultListener;
import com.tencent.qcloud.qiaoqiao.ui.tools.Constant;
import com.tencent.qcloud.qiaoqiao.ui.tools.MyAppUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.FormBody;
import okhttp3.RequestBody;


public class LikeUserVideoFragment extends BaseFragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.nodata_tv)
    TextView nodataTv;

    public static LikeUserVideoFragment newInstance() {
        LikeUserVideoFragment fragment = new LikeUserVideoFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    private List<TCVideoInfo> mVideoList;
    private List<CollectBean.ListBean> videoBeanList;
    private CollectAdapter videoAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_collect, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        videoBeanList = new ArrayList<>();
        mVideoList = new ArrayList<>();
        videoAdapter = new CollectAdapter();
        recyclerView.setAdapter(videoAdapter);
        videoAdapter.addData(videoBeanList);

//        //触发自动刷新
//        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        videoIndex = 1;
                        loadData();
                        refreshLayout.finishRefresh();
                        refreshLayout.setNoMoreData(false);
                    }
                });
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        loadData();
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    }
                });
            }
        });
        //触发自动刷新
//        refreshLayout.autoRefresh();
//        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
        videoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mVideoList = MyAppUtils.getPlayVideoData(videoBeanList);
                startLivePlay(mVideoList.get(position), position);
            }
        });
        loadData();
    }

    /**
     * 开始播放视频
     *
     * @param item 视频数据
     */
    private void startLivePlay(final TCVideoInfo item, int position) {
        Intent intent = new Intent(getActivity(), TCVodPlayerActivity.class);
        intent.putExtra(TCConstants.PLAY_URL, item.playurl);
        intent.putExtra(TCConstants.PUSHER_ID, item.userid);
        intent.putExtra(TCConstants.PUSHER_NAME, item.nickname == null ? item.userid : item.nickname);
        intent.putExtra(TCConstants.PUSHER_AVATAR, item.headpic);
        intent.putExtra(TCConstants.COVER_PIC, item.frontcover);
        intent.putExtra(TCConstants.FILE_ID, item.fileid != null ? item.fileid : "");
        intent.putExtra(TCConstants.TCLIVE_INFO_LIST, (Serializable) mVideoList);
        intent.putExtra(TCConstants.TIMESTAMP, item.createTime);
        intent.putExtra(TCConstants.TCLIVE_INFO_POSITION, position);
        startActivityForResult(intent, 100);
    }

    int videoIndex = 1;

    /**
     * 获取收藏
     */
    private void loadData() {
        if (TCUserMgr.getInstance().hasUser()) {
            nodataTv.setVisibility(View.VISIBLE);
            return;
        }
        RequestBody formBody = new FormBody.Builder()
                .add("userid", TCUserMgr.getInstance().getUserId())
                .add("index", videoIndex + "")
                .add("count", Constant.SIZE + "").build();
        HttpRequest.requestPost("watchlist", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                CollectBean collectBean = FastJsonTools.getPerson(data, CollectBean.class);
                if (collectBean != null) {
                    // mVideoList.addAll();
                    int size = collectBean.getTotal();
                    if (videoIndex <= 1) {
                        videoBeanList.clear();
                        videoAdapter.setNewData(videoBeanList);
                    }
                    if (size>0){
                        nodataTv.setVisibility(View.GONE);
                    }
                    videoIndex++;
                    try {
                        videoBeanList.addAll(collectBean.getList());
                        videoAdapter.setNewData(videoBeanList);
                        if (videoBeanList.size() >= size) {
                            videoAdapter.notifyDataSetChanged();
                            refreshLayout.finishLoadMoreWithNoMoreData();
                        }
                    } catch (Exception e) {

                    }

                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onFailure(String data) {
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
